import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Radio, Modal, Select, DatePicker } from 'antd'
import { UpOutlined, DownOutlined, ExclamationCircleOutlined, DownloadOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import CaseNoRender from '@components/CaseNoRender'
import style from './CaseManage.module.less'
import nStyle from './normal.module.less'
import { json2Excel } from '@js/excel'
import EditNote from '@components/CaseNote/EditModal'

const { Item } = Form
const { confirm } = Modal
const { Option } = Select

const layout = {
  labelCol: { flex: '96px' }
}

// 获取表格字段配置
function getColumns (refreshFn) {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '收案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      render: (v, l) => {
        return <CaseNoRender data={l} note refreshFn={refreshFn} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicants',
      key: 'applicants',
      width: '15%',
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    {
      title: '被申请人',
      dataIndex: 'respondents',
      key: 'respondents',
      width: '15%',
      render: v => {
        return (v || []).filter(li => li.status).map(li => li.name).join('、')
      }
    },
    // {
    //   title: '案由',
    //   dataIndex: 'cause_action',
    //   key: 'cause_action',
    //   ellipsis: true
    // },
    {
      title: '争议金额',
      dataIndex: 'dispute_amount',
      key: 'dispute_amount',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '仲裁费',
      dataIndex: 'fee',
      key: 'fee',
      render: v => {
        return String(v || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      }
    },
    {
      title: '案件状态',
      dataIndex: 'status',
      key: 'status',
      width: 80
    },
    {
      title: '立案员',
      dataIndex: 'accepter',
      key: 'accepter',
      width: 70
    },
    {
      title: '立案时间',
      dataIndex: 'docket_datetime',
      key: 'docket_datetime',
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      render: (value, line) => {
        if (line.cause_action) {
          return (
            <span className={style['operate-cell']}>
              <span onClick={() => this.openDetail(line)}>详情</span>
              <span onClick={() => this.modifyInfo(line)}>修改信息</span>
              <a className={nStyle['opearte-btn']} onClick={() => this.setState({ visible: true, modifyData: line })}>添加便签</a>
            </span>
          )
        }
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.openDetail(line)}>详情</span>
            <span onClick={() => this.fullInfo(line)}>完善信息</span>
            <a className={nStyle['opearte-btn']} onClick={() => this.setState({ visible: true, modifyData: line })}>添加便签</a>
          </span>
        )
      }
    }
  ]
}

class AcceptCaseManage extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '全部',
    visible: false,
    modifyData: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    condition: [],
    accepterList: []
  }

  formRef = React.createRef()

  openAcceptCase () {
    this.props.addWindow({ id: 'AcceptCase', title: '收案', componentName: 'AcceptCase' })
  }

  openPreAcceptCase () {
    this.props.addWindow({ id: 'PreAcceptCase', title: '预收案', componentName: 'PreAcceptCase' })
  }

  // 完善信息
  fullInfo (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `完善信息-${data.accept_no || data.serial_no}`, componentName: 'AcceptCase', forceRefresh: true, meta: { id: data.id, editable: true } })
  }

  // 完善信息
  modifyInfo (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `修改信息-${data.accept_no || data.serial_no}`, componentName: 'AcceptCase', forceRefresh: true, meta: { id: data.id, editable: true } })
  }

  // 查看案件详情
  openDetail (data) {
    this.props.addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id, editable: true } })
  }

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  formatForm (form) {
    const condition = []
    if (form.caseno_desc) {
      condition.push({ k: 'caseno_desc|acceptno_desc|counter_caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.applicant) {
      condition.push({ k: 'applicant_name', o: 'like', v: `%${form.applicant}%` })
    }
    if (form.respondent) {
      condition.push({ k: 'respondent_name', o: 'like', v: `%${form.respondent}%` })
    }
    if (form.accepter) {
      condition.push({ k: 'accepter', o: '=', v: form.accepter })
    }
    if (form.beginDate) {
      condition.push({ k: 'docket_datetime', o: '>=', v: Math.floor(form.beginDate / 1000) })
    }
    if (form.endDate) {
      condition.push({ k: 'docket_datetime', o: '<=', v: Math.floor(form.endDate / 1000) })
    }
    return condition
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, status } = this.state
    const { current, pageSize } = pagination
    const condition = this.formatForm(form)
    if (status === '7天未交费') {
      condition.push({ k: 'status', o: 'in', v: '立案' })
      condition.push({ k: 'docket_datetime', o: '<', v: Math.floor(Date.now() / 1000) - 604800 })
    } else if (status === '全部') {
      condition.push({ k: 'status', o: 'in', v: '已提交,立案,交费,不予受理,视为撤回仲裁申请' })
    } else if (status === '待确认交费') {
      condition.push({ k: 'status', o: 'in', v: '立案' })
    } else {
      condition.push({ k: 'status', o: 'in', v: status })
    }

    this.setState({ condition })
    this.setState({ loading: true })
    this.$get('/api/xapc/case', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {}, status } = this.props.meta || {}
    if (status) {
      this.setState({
        status
      })
    }
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    const condition = this.state.condition
    this.$get('/api/xapc/case', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          const caseno = l.caseno_desc || l.case_no || l.acceptno_desc || l.acceptno
          const date = l.docket_datetime ? moment(l.docket_datetime * 1000).format('YYYY-MM-DD') : ''
          return {
            序号: pageSize * (current - 1) + i + 1,
            案号: caseno + (l.delay_day ? '(缓)' : ''),
            申请人: (l.applicants || []).map(li => li.status ? li.name : li.name + '（终结）').join('、'),
            被申请人: (l.respondents || []).map(li => li.status ? li.name : li.name + '（终结）').join('、'),
            案由: l.cause_action,
            争议金额: l.dispute_amount || 0,
            仲裁费: l.fee || 0,
            案件状态: l.status,
            立案员: l.accepter,
            立案时间: date ? moment(date).toDate() : ''
          }
        })
        json2Excel([{ data: list, sheetname: '立案管理' }], '立案管理')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  initAccepterList () {
    this.$get('/api/xapc/employee/getCaseAccepter')
      .then(res => {
        if (res.status === 1) {
          this.setState({
            accepterList: res.data
          })
        }
      })
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
    this.initAccepterList()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this, () => this.getTableData())
    const { modifyData: m } = this.state
    return (
      <div className={style.container}>
        <EditNote visible={this.state.visible} caseid={m ? m.id : ''} caseno={m ? (m.caseno_desc || m.acceptno_desc) : ''} hide={() => this.setState({ visible: false })} data={this.state.modifyData} refreshFn={() => { this.setState({ visible: false, modifyData: null }); this.getTableData() }} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='accept_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='立案号' name='caseno_desc'>
                    <Input placeholder='请输入立案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='申请人' name='applicant'>
                    <Input placeholder='请输入申请人' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='被申请人' name='respondent'>
                    <Input placeholder='请输入被申请人' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='立案员' name='accepter'>
                    <Select allowClear placeholder='请选择'>
                      {this.state.accepterList.map((li, i) => <Option key={i} value={li.name}>{li.name}</Option>)}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='立案开始时间' name='beginDate'>
                    <DatePicker className={style.full} />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='立案结束时间' name='endDate'>
                    <DatePicker className={style.full} />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-btns-line']}>
          {/* <div className={style['table-left-btns']}>
            <Button type='primary' onClick={() => this.openAcceptCase()}>
              <span>+ 收案</span>
            </Button>
            <Button type='primary' onClick={() => this.openPreAcceptCase()}>
              <span>+ 预收案</span>
            </Button>
          </div> */}
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
          <div className={style['table-tabs-container']}>
            <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
              <Radio.Button value='全部'>全部</Radio.Button>
              <Radio.Button value='视为撤回仲裁申请'>视为撤回仲裁申请</Radio.Button>
              <Radio.Button value='已提交'>已提交</Radio.Button>
              <Radio.Button value='待确认交费'>待确认交费</Radio.Button>
              <Radio.Button value='交费'>交费</Radio.Button>
              <Radio.Button value='7天未交费'>7天未交费</Radio.Button>
              <Radio.Button value='不予受理'>不予受理</Radio.Button>
            </Radio.Group>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={v => this.tableChange(v)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(AcceptCaseManage)
